local vyVer = "0.8.5";
local vyCList = {};
local GameTooltip_obj = GameTooltip;
local GameTooltipHyperLink_obj = GameTooltipHyperLink;
local vyCards = {};

function vyParseCards()
	local vyCSum, vyCHave, data;
	vyCSum = 0;
	vyCHave = 0;
	local origName;
	for i = 0 , 16 do
		local cnt = LuaFunc_GetCardMaxCount(i);
		if( cnt ~= nil and cnt > 0 ) then
			for j = 1 , cnt do
				local CardID, CardFlag, CardName, CardTip = LuaFunc_GetCardInfo(i , j - 1);
				local vyhex = dec2hex(CardID);
				origName = CardName;
				-- check if an unknown card has name or not
				if (string.sub(CardName, 1, 1) == "?") then
					local tmp = vyCardInfo_GetCardName(vyhex);
					origName = tmp["name"];
				end
				if (origName ~= "") then
					vyCList[vyhex] = {};
					vyCList[vyhex]["Flag"] = CardFlag;
					vyCList[vyhex]["Tip"] = CardTip;
					vyCList[vyhex]["Cat"] = LuaFunc_GetString("SYS_RACE_" .. i);
					vyCSum = vyCSum + 1;
					data = vyCardInfo_GetCardName(vyhex);
					vyCards[data["name"]] = {};
					if (CardFlag == 1) then
						vyCHave = vyCHave + 1;
						vyCards[data["name"]]["have"] = true;
					else
						vyCards[data["name"]]["have"] = false;
					end
					vyCards[data["name"]]["color"] = data["color"];
					vyCards[data["name"]]["id"] = CardID;
				end
			end
		end
	end
	local perc = "|cff009900" .. math.floor(vyCHave / vyCSum * 100) .. "%|r";
	vyCSum = "|cffff0000" .. vyCSum .. "|r";
	vyCHave = "|cffff0000" .. vyCHave .. "|r";
	
	DEFAULT_CHAT_FRAME:AddMessage(string.format(vyCardInfoLocales["cardinfo"], vyCSum, vyCHave, perc));
end

function vyCardCheck(tooltip, link)
	if (link == nil) then
		return false;
	end
	local _, _, vyhex = string.find(link, ':([0-9a-f]+)');
	if (vyCList[vyhex] == nil) then
		return false;
	end
	tooltip:ClearLines();
	local data = vyCardInfo_GetCardName(vyhex);
	local name = data["name"];

	-- Name bug, Khazor Reindeer -> Huge-antlered Reindeer
--	if (vyhex == "bc028") then
--		name = "Huge-antlered Reindeer";
--	end
	tooltip:SetText("|cff" .. data["color"] .. vyCardInfoLocales["card"] .. " -" .. name .. "|r");

	tooltip:AddLine(vyCList[vyhex]["Tip"]);
	if (vyCList[vyhex]["Flag"] == 0) then
		tooltip:AddLine("|cffff0000" .. vyCardInfoLocales["donthave"] .. "|r");
	else
		tooltip:AddLine("|cff00ff00" .. vyCardInfoLocales["have"] .. "|r");
	end
	tooltip:AddLine(vyCardInfoLocales["category"] .. ": |cffffff00" .. vyCList[vyhex]["Cat"] .. "|r");

	local location;
	if (vyCardInfoMobDataFix[hex2dec(vyhex)]) then
		location = GetZoneLocalName(vyCardInfoMobDataFix[hex2dec(vyhex)]);
	elseif (vyCardInfoMobData[hex2dec(vyhex)]) then
		location = GetZoneLocalName(vyCardInfoMobData[hex2dec(vyhex)]);
	else
		location = vyCardInfoLocales["unknown"];
	end
	tooltip:AddLine(vyCardInfoLocales["location"] .. ": |cffffff00" .. location .. "|r");
--	tooltip:AddLine("ID: |cffffff00" .. hex2dec(vyhex) .. "|r");
end

function vyCardInfo_OnEvent(event)
	if (event == "CARDBOOKFRAME_UPDATE") then
		vyParseCards();
	end
	if (event == "UPDATE_MOUSEOVER_UNIT") then
		vyMouseOverUnit();
	end
--[[	
	if (event == "VARIABLES_LOADED") then
		if (vyMobAreas == nil or not vyMobAreas["manual"] or not vyMobAreas["npcsearch"]) then
			vyMobAreas = {};
			vyMobAreas["manual"] = {};
			vyMobAreas["npcsearch"] = {};
		end
		SaveVariables("vyMobAreas");
		--SaveVariables("MMODBData");
	end
]]	
	if (event == "VARIABLES_LOADED") then
		if (vyCardInfoMobDataFix == nil) then
			vyCardInfoMobDataFix = {};
		end
		SaveVariables("vyCardInfoMobDataFix");
	end
end

function vyCardInfo_GetCardName(id)
	vyCardInfoTooltip:SetText("")
	vyCardInfoTooltip:SetHyperLink("|Hitem:" .. id .. "|h|h")
	local r, g, b = vyCardInfoTooltipTextLeft1:GetColor();
	local color = SolPercentToHex(r*256) .. SolPercentToHex(g*256) .. SolPercentToHex(b*256);
	vyCardInfoTooltip:Hide();
	local name = vyCardInfoTooltipTextLeft1:GetText()
--	name = string.sub(name, 7)
	name = string.sub(name, string.len(vyCardInfoLocales["card"])+3);
	local data = {};
	-- Name bug, Khazor Reindeer -> Huge-antlered Reindeer
--	if (id == "bc028") then
--		name = "Huge-antlered Reindeer";
--	end
	data["name"] = name;
	data["color"] = color;
	return data;
end

function SolPercentToHex(percent)
	if (percent >= 255) then return "FF"; end
	if (percent == 0) then return "00";	end
	local c1 = dec2hex(math.floor(percent / 16));
	local c2 = dec2hex(math.floor(percent % 16));
	if (c1 == "") then c1 = "0"; end
	return c1 .. c2;
end


function vyMouseOverUnit()
	_G["vyCardToolTip"] = nil;
	if (not UnitCanAttack("player", "mouseover") or UnitIsPlayer("mouseover")) then
		return false;
	end
	local name = UnitName("mouseover");
	local checkarea = false;
	if (vyCards[name] == nil) then
		_G["vyCardToolTip"] = "vyCardInfo: |cffffff00" .. vyCardInfoLocales["notfound"] .. "|r";
	elseif (vyCards[name]["have"] == true) then
		local card =  "|r|cff" .. vyCards[name]["color"] .. vyCardInfoLocales["cardcolor"] .. "|r|cff00ff00";
		_G["vyCardToolTip"] = "vyCardInfo: |cff00ff00" .. string.format(vyCardInfoLocales["havecolor"] .. "|r", card);
		checkarea = true;
	else
		local card =  "|r|cff" .. vyCards[name]["color"] .. vyCardInfoLocales["cardcolor"] .. "|r|cffff0000";
		_G["vyCardToolTip"] = "vyCardInfo: |cffff0000" .. string.format(vyCardInfoLocales["donthavecolor"] .. "|r", card)
		checkarea = true;
	end
	GameTooltip:AddLine(_G["vyCardToolTip"]);

	if (checkarea == true) then
		local id = vyCards[name]["id"];
		local WMapID = GetCurrentWorldMapID();
		-- 770078: Morcus Beast / Aslan
		if (id ~= 770078 and vyCardInfoMobDataFix[id] == nil and WMapID > 0 and WMapID ~= vyCardInfoMobData[id]) then
			vyCardInfoMobDataFix[id] = WMapID;
			DEFAULT_CHAT_FRAME:AddMessage("|cffff0000vyCardInfo: " .. string.format(vyCardInfoLocales["update"], name) .. "|r");
			SaveVariables("vyCardInfoMobDataFix");
		end
	end
end

function vyCardInfo_OnUpdate(this)
end

function vyCardInfo_OnLoad(this)
	local str = "vyCardInfo "..vyVer.." by Vaily loaded.";
	DEFAULT_CHAT_FRAME:AddMessage(str);
	local lang = GetLanguage():upper();
	local locfile = "Interface/Addons/vyCardInfo/locales/" .. lang .. ".lua";
	local _, e = loadfile(locfile);
	if (e) then
		locfile = "Interface/Addons/vyCardInfo/locales/ENEU.lua";
		loadfile(locfile);
	end
	dofile(locfile);
	vyParseCards();
end

function dec2hex(dec)
	return string.format("%x", dec);
end

function hex2dec(hex)
	return tonumber(hex, 16)
end

local SetAuctionBrowseItem_orig = GameTooltip_obj["SetAuctionBrowseItem"];
function GameTooltip:SetAuctionBrowseItem(id)
	SetAuctionBrowseItem_orig(GameTooltip_obj, id);
	vyCardCheck(self, GetAuctionBrowseItemLink(id));
end

local SetBagItem_orig = GameTooltip_obj["SetBagItem"];
function GameTooltip:SetBagItem(id)
	SetBagItem_orig (GameTooltip_obj, id);
	vyCardCheck(self, GetBagItemLink(id));
end

local SetBankItem_orig = GameTooltip_obj["SetBankItem"];
function GameTooltip:SetBankItem(id)
	SetBankItem_orig(GameTooltip_obj, id);
	vyCardCheck(self, GetBankItemLink(id));
end

local SetBootyItem_orig = GameTooltip_obj['SetBootyItem'];
function GameTooltip:SetBootyItem(id)
	SetBootyItem_orig(GameTooltip_obj, id);
	vyCardCheck(self, GetBootyItemLink(id));
end


-- Inventory Viewer 1.4+
-- thx to: Zilvermoon
if (GameTooltip_obj["SetHouseItem"]) then
	local SetHouseItem_orig = GameTooltip_obj["SetHouseItem"];
	function GameTooltip:SetHouseItem(ParentDBID,ButtonId)
		SetHouseItem_orig(GameTooltip_obj,ParentDBID,ButtonId);
		vyCardCheck(self, Houses_GetItemLink(ParentDBID,ButtonId));
	end

	local SetStoreItem_orig = GameTooltip_obj["SetStoreItem"];
	function GameTooltip:SetStoreItem(tab,ButtonId)
		SetStoreItem_orig(GameTooltip_obj,tab,ButtonId);
		if (tab == "SELL") then
			vyCardCheck(self,GetStoreSellItemLink(ButtonId));
		elseif (tab == "BUYBACK") then
			vyCardCheck(self,GetStoreBuyBackItemLink(ButtonId));
		end
	end

	local IVSetHyperLink_orig = GameTooltip_obj["SetHyperLink"];
	function GameTooltip:SetHyperLink(link)
		IVSetHyperLink_orig(GameTooltip_obj, link);
		vyCardCheck(self, link);
	end
end

local SetHyperLink_orig = GameTooltipHyperLink_obj["SetHyperLink"];
function GameTooltipHyperLink:SetHyperLink(link)
	SetHyperLink_orig(GameTooltipHyperLink_obj, link);
	vyCardCheck(self, link);
end

-- Advanced Auctionhouse 1.2+
-- thx to: Graves
if(AA_Tooltip) then
	local AA_Tooltip_obj = AA_Tooltip;
	local SetHyperLink_orig = AA_Tooltip_obj["SetHyperLink"];
	function AA_Tooltip:SetHyperLink(link)
		SetHyperLink_orig(AA_Tooltip_obj, link);
		vyCardCheck(self, link);
	end
end